<!--
 * @Author: Vben
 * @Description: Multi-language switching component
-->
<template>
  <div>
    <Dropdown
      placement="bottom"
      :trigger="['click']"
      :dropMenuList="domainList"
      :selectedKeys="selectedKeys"
      @menuEvent="handleMenuEvent"
      overlayClassName="app-locale-picker-overlay"
    >
      <span class="cursor-pointer text-light-500 flex items-center" :class="[iconColor]">
        <!-- <Icon icon="iconoir:settings-profiles" /> -->
        <Icon :icon="icon" />
        <span v-if="showText" class="ml-1">{{ getDomainText }}</span>
      </span>
    </Dropdown>
  </div>
</template>

<script lang="ts" setup>
  import type { LocaleType } from '/#/config';
  import type { DropMenu } from '/@/components/Dropdown';
  import { ref, watchEffect, unref, computed, PropType } from 'vue';
  import { Dropdown } from '/@/components/Dropdown';
  import { Icon } from '/@/components/Icon';
  import { useDomain } from '/@/locales/useDomain';

  const props = defineProps({
    /**
     * Whether to display text
     */
    showText: { type: Boolean, default: true },
    /**
     * Whether to refresh the interface when changing
     */
    reload: { type: Boolean },
    domainList: {
      type: Array as PropType<(DropMenu & Recordable)[]>,
      default: () => [],
    },
    icon: {
      type: String,
      default: 'ion:settings-outline',
    },
    iconColor: {
      type: String,
      default: '',
    },
  });

  // const { file } = useGlobSetting();
  // const ss = createSessionStorage();

  const selectedKeys = ref<string[]>([]);

  const { changeTenantId, getTenantId, getDomain } = useDomain();

  const getDomainText = computed(() => {
    const key = selectedKeys.value[0];
    if (!key) {
      return '';
    }
    return props.domainList.find((item) => item.event === key)?.text;
  });

  watchEffect(() => {
    const id = unref(getTenantId);
    const tenantId = getDomain.value && id ? id : (props.domainList[0].event as string);
    selectedKeys.value = [tenantId];
  });

  async function toggleLocale(lang: string) {
    // 通过http head传递
    await changeTenantId(lang as LocaleType);
    selectedKeys.value = [lang as string];
    props.reload && location.reload();
  }

  function handleMenuEvent(menu: DropMenu) {
    if (unref(getTenantId) === menu.event) {
      return;
    }
    // ss.get(MENUID_KEY) && ss.set(MENUID_KEY, null);
    // permissionStore.setFirstMenuParams(null);

    toggleLocale(menu.event as string);
  }
</script>

<style lang="less">
  .app-locale-picker-overlay {
    height: 400px;
    overflow-y: scroll;

    .ant-dropdown-menu-item {
      min-width: 160px;
    }
  }
</style>
